﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

using QuDao;
using FineUICore;
using Kalman;
using Kalman.Extensions;
using Microsoft.AspNetCore.Http;
using AliyunOss;

namespace AdminUI.Pages.BaseData
{
    public partial class VideoAddModel : BaseModel
    {
        readonly AliyunOssClient oss;
        public VideoAddModel(AliyunOssClient ossClient)
        {
            oss = ossClient;
        }

        public void OnGet(int rid)
        {
            GoodsID = rid;
        }

        /// <summary>
        /// 
        /// </summary>
        public int GoodsID { get; set; }

        public IActionResult OnPostSource_SelectedIndexChanged(int selected)
        {
            var video = UIHelper.FileUpload("VideoUrl");
            var live = UIHelper.TextBox("LiveUrl");
            if(selected != 2)
            {
                video.Hidden(false);
                live.Hidden(true);
            }
            else
            {
                video.Hidden(true);
                live.Hidden(false);
            }

            return UIHelper.Result();
        }

        public IActionResult OnPostBtnSubmit_Click(VideoAddDto dto, IFormFile coverUrl, IFormFile videoUrl, int source, string liveUrl)
        {
            try
            {
                if (coverUrl != null)
                {
                    var img = UploadImage(oss, coverUrl);
                    if (img != null)
                    {
                        dto.CoverUrl = img.OssUrl;
                    }
                }
                if (videoUrl != null && source == 1)
                {
                    var file = UploadVideo(oss, videoUrl, 20);
                    if (file != null)
                    {
                        dto.VideoUrl = file.OssUrl;
                        dto.FileSize = (int)file.FileSize;
                    }
                }
                else
                {
                    dto.VideoUrl = liveUrl;
                }

                var id = VideoBO.Instance.Add(dto);
                LogAction(ActionType.新增, $"新增视频：{id}-{dto.Memo}");

                FineUICore.PageContext.RegisterStartupScript(ActiveWindow.GetHideRefreshReference());
                //ActiveWindow.HidePostBack();
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                if (!(ex is AppException && ex.InnerException == null))
                {
                    msg = ex.ToString();
                }

                Alert.Show(msg, "错误信息", MessageBoxIcon.Error);
            }

            return UIHelper.Result();
        }

    }
}